import React from 'react'
import { Form, Button, Space } from 'antd'
import type { FormProps } from 'antd'

interface ProFormProps extends FormProps {
  onFinish?: (values: any) => Promise<void> | void
  onReset?: () => void
  submitter?: false | {
    submitText?: string
    resetText?: string
    submitButtonProps?: Record<string, any>
    resetButtonProps?: Record<string, any>
  }
  loading?: boolean
  children?: React.ReactNode
}

/**
 * 增强型表单组件
 * @description 基于 Ant Design Form 的封装，提供了更便捷的提交和重置功能
 * 
 * @example
 * ```tsx
 * <ProForm
 *   onFinish={handleSubmit}
 *   onReset={handleReset}
 *   loading={loading}
 *   submitter={{
 *     submitText: '保存',
 *     resetText: '重置'
 *   }}
 * >
 *   <Form.Item name="name" label="姓名">
 *     <Input />
 *   </Form.Item>
 * </ProForm>
 * ```
 * 
 * @param onFinish - 表单提交回调
 * @param onReset - 表单重置回调
 * @param loading - 提交按钮加载状态
 * @param submitter - 提交按钮配置，设为 false 可隐藏
 */
const ProForm: React.FC<ProFormProps> = ({
  children,
  onFinish,
  onReset,
  submitter = {},
  loading,
  ...props
}) => {
  const [form] = Form.useForm()

  const handleReset = () => {
    form.resetFields()
    onReset?.()
  }

  const renderSubmitter = () => {
    if (submitter === false) return null

    const {
      submitText = '提交',
      resetText = '重置',
      submitButtonProps = {},
      resetButtonProps = {}
    } = submitter

    return (
      <Form.Item>
        <Space>
          <Button
            type="primary"
            htmlType="submit"
            loading={loading}
            {...submitButtonProps}
          >
            {submitText}
          </Button>
          <Button
            onClick={handleReset}
            {...resetButtonProps}
          >
            {resetText}
          </Button>
        </Space>
      </Form.Item>
    )
  }

  return (
    <Form
      form={form}
      onFinish={onFinish}
      {...props}
    >
      {children}
      {renderSubmitter()}
    </Form>
  )
}

export default ProForm 